package com.gupao.chat.client2;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.Socket;
import java.util.Random;
import java.util.Scanner;

@Configuration
@Slf4j
public class ChatClient2 {
    @Value("${client.server.ip}")
    private String serverIp;
    @Value("${client.server.port}")
    private int serverPort;
    private static Socket socket;
    private String info;

    @Bean
    public void startClient() {
        try {
            socket = new Socket(serverIp, serverPort);

            int randomNumber = (int) (Math.random() * 100) + 1;
            if (socket.isConnected()) {
                writeMessage(randomNumber);

                readMessage();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void readMessage() {
        new Thread(() -> {
            while (socket != null && socket.isConnected()) {
                String message = null;
                BufferedReader bufferedReader;
                try {
                    bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    message = bufferedReader.readLine();
                    if (!StringUtils.isEmpty(message)) {
                        System.out.println(message);
                        System.out.println("请输入你的请求：");
                    }
                } catch (IOException e) {
                    log.info(e.getMessage());
                    try {
                        if (socket != null) {
                            socket.close();
                            socket = null;
                        }
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }).start();
    }

    private void writeMessage(int randomNumber) {
        new Thread(() -> {
            Scanner scanner = new Scanner(System.in);
            System.out.println("已连接服务端，请输入你的请求：\n");
            while (socket != null && socket.isConnected()) {
                info = scanner.nextLine();
                DataOutputStream dos = null;
                try {
                    dos = new DataOutputStream(socket.getOutputStream());
                    dos.writeUTF("client(" + randomNumber + "):" + info + "\n");
                    dos.flush();
                } catch (IOException e) {
                    log.info(e.getMessage());
                    try {
                        scanner.close();
                        socket.close();
                        socket = null;
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }).start();
    }
}
